package com.dlc.shop.user.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.CouponOverdueEvent;
import com.dlc.shop.user.common.model.UserLevelCoupon;
import com.dlc.shop.user.common.service.UserLevelCouponService;
import com.dlc.shop.user.common.service.UserLevelRightsService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gaozijie
 * @date 2023-04-20
 */
@Component
@AllArgsConstructor
public class UserCouponOverdueListener {

    private final Logger logger = LoggerFactory.getLogger(UserCouponOverdueListener.class);
    private final UserLevelCouponService userLevelCouponService;
    private final UserLevelRightsService userLevelRightsService;


    @EventListener(CouponOverdueEvent.class)
    public void updateLevelCoupon(CouponOverdueEvent event) {
        logger.info("===== update the level-coupon ...=====");
        List<Long> couponIds = event.getCouponIds();
        if (CollectionUtils.isEmpty(couponIds)) {
            return;
        }
        // 查出优惠券关联的会员等级
        List<Long> levelIds = userLevelCouponService.listLevelIdByCouponIds(couponIds);
        if (CollectionUtils.isEmpty(levelIds)) {
            return;
        }
        // 删除优惠券与会员等级的关联
        userLevelCouponService.remove(new LambdaQueryWrapper<UserLevelCoupon>()
                .in(UserLevelCoupon::getCouponId, couponIds));
        // 重新统计会员等级的优惠券数量
        Map<Long, Integer> levelCouponNumsMap = userLevelCouponService.countLevelCouponNums(levelIds);
        List<Long> removeLevelIds = new ArrayList<>();
        for (Long levelId : levelIds) {
            Integer couponNum = levelCouponNumsMap.get(levelId);
            if (couponNum == null || couponNum == 0) {
                removeLevelIds.add(levelId);
            }
        }
        // 将优惠券数量为0的会员等级，删除"送优惠券"的权益
        if (!CollectionUtils.isEmpty(removeLevelIds)) {
            userLevelRightsService.removeCouponRightsByLevelIds(removeLevelIds);
        }
    }
}
